<template>
  <div>
    <el-tabs size="mini" v-model="activeName" type="card" :before-leave='leaveTab' @tab-click="handleClick">
      <el-tab-pane label="基本信息" name="0">
        <el-form class="form-container" :model="form" :rules="(form.cardType > 0 || form.isPackage) ? rulesCard : rules"
          ref="postForm" label-width="200px" v-loading="loading">
          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item label="商品名称：" prop="title">
                <el-input size="mini" v-model="form.title" placeholder="请输入商品名称" :disabled="is_view" />
              </el-form-item>
              <el-form-item label="商品主图：" prop="listImgUrl">
                <pic-sel v-if="!form.listImgUrl" v-model="form.listImgUrl"></pic-sel>
                <pic-view v-else v-model="form.listImgUrl"></pic-view>
              </el-form-item>
              <el-form-item label="商品图片：" prop="imgUrls">
                <pic-sel v-if="!form.listImgUrl" v-model="form.imgUrls" :maxNum="9"></pic-sel>
                <pic-view v-else v-model="form.imgUrls"></pic-view>
              </el-form-item>
              <!-- <el-form-item label="商品视频：" prop="mainVideo">
                            </el-form-item> -->
              <template v-if="form.isPackage">
                <el-form-item label="关联商品：">
                  <el-button size="mini" class="ml10" @click="addItem()" type="primary"
                    icon="el-icon-plus">选择商品</el-button>
                  <table class="ikd-input-table ik-table-layout-fixed">
                    <thead>
                      <tr>
                        <th nowrap>序号</th>
                        <th nowrap>商品名称</th>
                        <th nowrap>商品规格</th>
                        <th nowrap>总库存</th>
                        <th nowrap>供货成本</th>
                        <th nowrap>物流成本</th>
                        <th nowrap>售价</th>
                        <th nowrap>优惠价</th>
                        <th nowrap style="width:100px;">操作</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="(item, idx) in form.items" :key="item.id">
                        <td>{{ idx + 1 }}</td>
                        <td>{{ item.title }}</td>
                        <td>{{ item.attribute }}</td>
                        <td>{{ item.inventory }}</td>
                        <td>{{ item.supplyPrice }}</td>
                        <td>{{ item.freightPrice }}</td>
                        <td>{{ item.price }}</td>
                        <td><el-input type="number" size="mini" class="w100" v-model="item.salePrice" maxlength="10"
                            @blur="makeMinSalePrice" /></td>
                        <td>
                          <el-button type="text" @click="addItem(idx)">编辑</el-button>
                          <el-button type="text" @click="removeItem(idx)">删除</el-button>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </el-form-item>
                <el-form-item label="套餐售价：" prop="minSalePrice">
                  <el-input type="number" size="mini" class="w100" v-model="form.minSalePrice" placeholder=""
                    disabled />
                </el-form-item>

              </template>
              <el-form-item label="分类1：" prop="catIds" v-if="!form.cardType && !form.isPackage">
                <el-cascader style="width:100%;" filterable :props="{ value: 'id', label: 'name', checkStrictly: true }"
                  size="mini" v-model="form.catIds" :disabled="is_view" :options="cateList"></el-cascader>
              </el-form-item>
              <el-form-item label="分类2：" prop="catIds2" v-if="!form.cardType && !form.isPackage">
                <el-cascader clearable style="width:100%;" filterable
                  :props="{ value: 'id', label: 'name', checkStrictly: true }" size="mini" v-model="form.catIds2"
                  :disabled="is_view" :options="cateList"></el-cascader>
              </el-form-item>
              <el-form-item label="配送方式：" prop="shippingMethod">
                <el-radio-group :disabled="is_view" v-model="form.shippingMethod">
                  <el-radio :label="0">到店自提</el-radio>
                  <el-radio :label="1">发货</el-radio>
                  <el-radio :label="2">自提+发货</el-radio>
                </el-radio-group>
              </el-form-item>
              <template v-if="!form.cardType">
                <el-form-item label="运费计算方式：" prop="useFreightTemplate">
                  <el-radio-group :disabled="is_view" v-model="form.useFreightTemplate">
                    <el-radio :label="1">使用运费模板</el-radio>
                    <el-radio :label="0">固定运费</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="运费模板：" prop="freightTemplateId" v-if="form.useFreightTemplate == 1">
                  <el-select clearable :disabled="is_view" size="mini" v-model="form.freightTemplateId"
                    placeholder="运费模板">
                    <el-option v-for="item in freightTemplateList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="固定运费：" prop="freightAmount" v-else>
                  <el-input class="w100" maxlength="6" type="number" size="mini" v-model="form.freightAmount"
                    :disabled="is_view" />
                </el-form-item>
              </template>
              <!-- <el-form-item label="包邮件数：" prop="freeFreightNum">
                                <el-input class="w100" maxlength="3" type="number" size="mini" v-model="form.freeFreightNum" :disabled="is_view" />
                                <p>设置包邮件数，是指n件起包邮，未达到包邮条件的需要增收运费，未设置默认为0，表示不包邮</p>
                            </el-form-item> -->
              <el-form-item label="是否新人购：" prop="limitUser" v-if="!form.cardType && !form.isPackage">
                <el-radio-group :disabled="is_view" v-model="form.limitUser">
                  <el-radio :label="0">否</el-radio>
                  <el-radio :label="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="核销人员：" prop="memberMobile" v-if="form.isVerification == 2"> {{ memberMobile }}
                <el-button type="primary" size="mini" @click="selects()">选择</el-button>
              </el-form-item>
              <el-form-item label="提货地址：" prop="address" v-if="form.isVerification == 2">{{ address }}
                <el-button type="primary" size="mini" @click="select()">选择</el-button>
              </el-form-item>
              <!-- <el-form-item label="禁止下单区域" prop="describe" v-if="!form.cardType">
                                <el-cascader
                                    style="width:100%;"
                                    filterable
                                    :props="{ value: 'id', label: 'name', children:'areas', multiple: true, checkStrictly: true }"
                                    size="mini"
                                    v-model="form.excludeRegions"
                                    :options="regionGroups"></el-cascader>
                            </el-form-item> -->
              <el-form-item v-if="!is_view">
                <el-button type="primary" size="mini" @click="next()">下一步</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <template v-if="!form.isPackage">
        <el-tab-pane label="价格/库存" name="1" v-if="form.cardType > 0">
          <el-form class="form-container" :model="form" :rules="rules2" ref="postForm2" label-width="200px"
            v-loading="loading">

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="规格类型：" prop="hasSku">
                  <el-radio-group :disabled="is_view" v-model="form.hasSku">
                    <el-radio :label="0">无</el-radio>
                    <el-radio :label="1">多规格商品</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="商品规格：" v-show="form.hasSku == 1">
                  <div class="attr_box">
                    <div class="item" v-for="(item, idx) in skuList" :key="item.id">
                      <div class="line">
                        <div class="name">规格名：</div>
                        <div class="line-val">
                          <el-input size="mini" :disabled="is_view" v-model="item.attrName" placeholder="请填写规格名称" />
                        </div>
                      </div>
                      <div class="line">
                        <div class="name">规格值：</div>
                        <div class="line-val" v-for="(item2, idx2) in item.items" :key="item2.id">
                          <el-input size="mini" :disabled="is_view" v-model="item2.attrValue"
                            :placeholder="getSkuPlaceHolder(idx2)" />
                        </div>
                      </div>
                      <div class="line">
                        <el-button type="text" size="mini" v-if="!is_view" @click="addSkuItem(idx)">添加子规格</el-button>
                      </div>
                    </div>
                  </div>
                  <el-button v-if="!is_view" type="primary" size="mini" @click="addSku()">添加规格</el-button>
                  <el-button v-if="!is_view" type="primary" size="mini" @click="makeSku()">生成规格明细</el-button>
                </el-form-item>
                <table v-show="form.hasSku == 1" id="product-attribute-table"
                  class="ikd-input-table ik-table-layout-fixed">
                  <thead>
                    <tr>
                      <th nowrap></th>
                      <th nowrap>规格名</th>
                      <th nowrap>规格值</th>
                      <th nowrap>图片</th>
                      <th nowrap>库存</th>
                      <th nowrap>最低数量</th>
                      <th nowrap>售价(元)<el-button v-if="!is_view" type="text" class="ml10"
                          @click="batchSalePrice()">批量</el-button></th>
                    </tr>
                  </thead>
                  <tbody>
                    <template v-for="(item, idx) in form.skuInfo">
                      <tr :key="item.id" :class="{ 'focus': item.profit < 0 }">
                        <td nowrap>
                          {{ idx + 1 }}
                        </td>
                        <td>{{ item.name }}</td>
                        <td>{{ item.value }}</td>
                        <td><pic-sel v-model="item.imgUrl"></pic-sel></td>
                        <td><el-input size="mini" type="number" :disabled="is_view" v-model="item.inventory" /></td>
                        <td><el-input size="mini" type="number" :disabled="is_view" v-model="item.minNum"
                            @blur="makeMinNum" /></td>
                        <td><el-input size="mini" @change="blurSalePrice(item)" type="number" :disabled="is_view"
                            @blur="makeMinSalePrice" v-model="item.salePrice" /></td>
                      </tr>
                    </template>
                  </tbody>
                </table>
                <el-form-item label="售价：" prop="minSalePrice">
                  <el-input type="number" size="mini" class="w100" v-model="form.minSalePrice" placeholder=""
                    :disabled="is_view || form.hasSku == 1" />
                </el-form-item>
                <el-form-item label="商品库存：" prop="inventory">
                  <el-input type="number" size="mini" class="w100" v-model="form.inventory" placeholder=""
                    :disabled="is_view || form.hasSku == 1" />
                </el-form-item>
                <el-form-item label="最低数量：" prop="minNum">
                  <el-input type="number" size="mini" class="w100" v-model="form.minNum" placeholder=""
                    :disabled="is_view || form.hasSku == 1" />
                </el-form-item>
                <!-- <el-form-item label="供货成本：" prop="minSupplyPrice">{{form.minSupplyPrice}}</el-form-item>
                                <el-form-item label="物流成本：" prop="minSupplyPrice">{{form.freightPrice}}</el-form-item>
                                <el-form-item label="售价：" prop="minSalePrice">
                                    <el-input type="number" size="mini" class="w100"  v-model="form.minSalePrice" placeholder="" :disabled="is_view || form.hasSku==1" />
                                </el-form-item> -->
                <el-form-item v-if="!is_view">
                  <el-button type="primary" size="mini" @click="prev()">上一步</el-button>
                  <el-button type="primary" size="mini" @click="next()">下一步</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="sku信息" name="1" v-else>
          <el-form class="form-container" :model="form" :rules="rules2" ref="postForm2" label-width="200px"
            v-loading="loading">
            <el-row :gutter="20">
              <el-col :span="24">
                <!-- <el-form-item label="规格类型：" prop="hasSku">
                                    <el-radio-group disabled v-model="form.hasSku">
                                        <el-radio :label="0">无</el-radio>
                                        <el-radio :label="1">多规格商品</el-radio>
                                    </el-radio-group>
                                </el-form-item> -->
                <el-form-item label="商品规格：">
                  <div class="attr_box">
                    <div class="item" v-for="(item) in skuList" :key="item.id">
                      <div class="line">
                        <div class="name">规格名：</div>
                        <div class="line-val">
                          <el-input size="mini" v-model="item.attrName" placeholder="请填写规格名称" />
                        </div>
                      </div>
                      <div class="line">
                        <div class="name">规格值：</div>
                        <div class="line-val" v-for="(item2, idx2) in item.items" :key="item2.id">
                          <el-input size="mini" v-model="item2.attrValue" :placeholder="getSkuPlaceHolder(idx2)" />
                        </div>
                      </div>
                    </div>
                  </div>
                </el-form-item>
                <div>
                  <div>红包抵扣</div>
                  <el-radio-group v-model="redChageType">
                    <div style="display: flex;">
                      <el-radio :label="1">按比例</el-radio>

                      <el-input type="number" size="mini" class="w200" v-model="redB" placeholder=""
                        @change="changeFreightTemplateAmount(1)">
                        <p class="note_back" slot="suffix">%</p>
                      </el-input>
                      <div style="font-size: 12px; line-height: 30px;">
                        设置红包可以抵扣的金额，基数是供货价格+运费， 例如基数是60，比利是500%； 红包抵扣值是300，如有小数点取整；
                      </div>



                    </div>
                    <div style="display: flex;">
                      <el-radio :label="2">按固定</el-radio>

                      <el-input type="number" size="mini" class="w200" v-model="redA" placeholder="请输入金额"
                        @change="changeFreightTemplateAmount(2)">
                        <p class="note_back" slot="suffix">元</p>
                      </el-input>
                      <div style="font-size: 12px; line-height: 30px;">
                        设置红包可以抵扣的金额，固定值设置300；红包抵扣值是300；
                      </div>

                    </div>

                  </el-radio-group>

                </div>
                <el-button type="primary" size="mini" @click="AddSkus()">添加规格</el-button>
                <table id="product-attribute-table" class="ikd-input-table ik-table-layout-fixed">
                  <thead>
                    <tr>
                      <th nowrap></th>
                      <th nowrap>SKU编号1</th>
                      <th nowrap>规格名</th>
                      <th nowrap>规格值</th>
                      <th nowrap>图片</th>
                      <th nowrap>库存</th>
                      <th nowrap>供货成本(元)</th>
                      <th nowrap>运费成本(元)</th>
                      <th nowrap>售价(元)<el-button v-if="!is_view" type="text" class="ml10"
                          @click="batchSalePrice()">批量</el-button></th>
                      <th nowrap>建议零售价(元)</th>
                      <th nowrap>虚拟销量<el-button v-if="!is_view" type="text" class="ml10"
                          @click="batchVirtualSaleCount()">批量</el-button></th>
                      <th nowrap>红包<el-button v-if="!is_view" type="text" class="ml10"
                          @click="batchRedpacket()">批量</el-button>
                      </th>
                      <!-- <th nowrap>实付价</th> -->
                      <th nowrap>利润</th>
                      <th nowrap>操作</th>
                      <!-- <th nowrap>库存</th> -->
                    </tr>
                  </thead>
                  <tbody>
                    <template v-for="(item, idx) in form.skuInfo">
                      <tr :key="item.id" :class="{ 'focus': item.profit < 0 }">
                        <td nowrap>
                          {{ idx + 1 }}
                        </td>

                        <td>
                          <!-- {{ item.ycSkuInfoId }} -->
                          <el-input size="mini" type="text" v-model="item.ycSkuInfoId" />
                        </td>
                        <td><el-input size="mini" disabled type="text" v-model="item.name" /></td>
                        <td><el-input size="mini" disabled type="text" v-model="item.value" /></td>
                        <td>
                          <!-- <pic-view v-model="item.imgUrl"></pic-view> -->
                          <pic-sel v-model="item.imgUrl"></pic-sel>
                          <!-- <pic-view v-else v-model="item.imgUrl"></pic-view> -->
                        </td>
                        <td><el-input size="mini" type="text" v-model="item.inventory" /></td>
                        <td><el-input size="mini" type="text" v-model="item.supplyPrice" /></td>
                        <td><el-input size="mini" type="text" v-model="item.freightPrice" /></td>
                        <td><el-input size="mini" @change="blurSalePrice(item)" type="number" :disabled="is_view"
                            @blur="makeMinSalePrice" v-model="item.salePrice" /></td>
                        <td><el-input size="mini" type="text" v-model="item.ycSalePrice" /></td>
                        <td><el-input size="mini" type="number" :disabled="is_view" v-model="item.virtualSaleCount"
                            @blur="makeVirtualSaleCount" /></td>
                        <td><el-input size="mini" @change="blurRedpacket(item)" type="number" :disabled="is_view"
                            @blur="makeMinSalePrice" v-model="item.redpacket" /></td>
                        <!-- <td>{{ item.actualPrice }}</td> -->
                        <td><el-input size="mini" type="text" v-model="item.profit" /></td>
                        <td>
                          <el-button :disabled="is_view" size="mini" @click="setShow(item)">{{ item.isShow == 1 ? '隐藏' :
                            '显示' }}</el-button>
                          <el-button :disabled="is_view" size="mini" @click="delSku(idx)" v-if="idx > 0">删除</el-button>
                        </td>
                        <!-- <td>{{item.inventory}}</td> -->
                      </tr>
                    </template>
                  </tbody>
                </table>
                <!-- <el-form-item label="供货成本：" prop="minSupplyPrice">{{form.minSupplyPrice}}</el-form-item>
                                <el-form-item label="物流成本：" prop="minSupplyPrice">{{form.freightPrice}}</el-form-item>
                                <el-form-item label="售价：" prop="minSalePrice">
                                    <el-input type="number" size="mini" class="w100"  v-model="form.minSalePrice" placeholder="" :disabled="is_view || form.hasSku==1" />
                                </el-form-item> -->
                <el-form-item label="虚拟销量：" prop="virtualSaleCount">
                  <el-input type="number" size="mini" class="w100" v-model="form.virtualSaleCount" placeholder=""
                    :disabled="is_view || form.hasSku == 1" />
                </el-form-item>
                <el-form-item v-if="!is_view">
                  <el-button type="primary" size="mini" @click="prev()">上一步</el-button>
                  <el-button type="primary" size="mini" @click="next()">下一步</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>

      </template>

      <el-tab-pane label="商品详情" name="2">
        <el-form class="form-container" :model="form" :rules="rules3" ref="postForm3" label-width="200px"
          v-loading="loading">
          <el-row :gutter="20">
            <el-col :span="24">
              <vue-ueditor-wrap @ready="editorReady" v-model="form.desc" :config="editorConfig"
                @beforeInit="addCustomButtom" />
              <el-form-item v-if="!is_view">
                <el-button type="primary" size="mini" @click="prev()">上一步</el-button>
                <el-button type="primary" size="mini" @click="next()">保存</el-button>
                <!-- <el-button v-if="!form.id || form.auditStatus==0" type="primary" size="mini" @click="next(1)">保存并提交审核</el-button> -->
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

      </el-tab-pane>
    </el-tabs>
    <pic-list :maxNum="0" :showPicDialog="showPicDialog" @on-selected="picOnSelected" @on-close="picOnClose" />
    <el-dialog title="选择用户" :visible.sync="dialogMemberVisibles" :close-on-click-modal="false" width="900px">
      <member-list :formData.sync="memberForm" @okSelect="okSelectMember" />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="dialogMemberVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择用户" :visible.sync="dialogMemberVisible" :close-on-click-modal="false" width="900px">
      <address-list :formData.sync="memberForm" @okSelects="okSelectAddress" />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="dialogMemberVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="dialogBatchTitle" :visible.sync="dialogBatchVisible" :close-on-click-modal="false" width="300px">
      <el-form :model="batchForm" ref="batchForm" label-width="80px">
        <template v-if="batchType == 'sale'">
          <el-form-item label="类型：" prop="type">
            <el-radio-group v-model="batchForm.type">
              <el-radio :label="0">固定值</el-radio>
              <el-radio :label="1">上浮比例</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="batchLabel" prop="value">
            <el-input size="mini" type="number" :placeholder="batchForm.type == 1 ? '上浮的百分比' : ''" maxlength="10"
              v-model="batchForm.value" />
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item :label="batchLabel" prop="value">
            <el-input size="mini" type="number" placeholder="" maxlength="10" v-model="batchForm.value" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogBatchVisible = false">取消</el-button>
        <el-button size="mini" type="primary" @click="okBatch">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择商品" :visible.sync="dialogProductVisible" :close-on-click-modal="false" width="1000px">
      <product-list :formData.sync="productSelectForm" @okSkuSelect="okSelectProduct" />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="dialogProductVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import VueUeditorWrap from 'vue-ueditor-wrap'
import {
  product_save,
  product_detail,
  product_freight_template_list,
  region_group_list
} from '../../api/product';
import {
  yc_detail
} from '../../api/yc';
import {
  product_cat_tree
} from '../../api/product';
import {
  _axios
} from '../../api/index';
// import {
//     age_list
// } from '../../utils/utils';
// import {
//     org_school_tree
// } from '../../api/org/index';
// import {
//     isInteger
// } from '../../utils/validator'
// import {
//     next_no
// } from '../../api/sys';

export default {
  name: 'agency-create',
  components: {
    'member-list': () => import('../../components/Member/index'),
    'pic-sel': () => import('../../components/PicSel/index'),
    'pic-view': () => import('../../components/PicView/index'),
    'pic-list': () => import('../../components/PicSel/list'),
    VueUeditorWrap,
    'product-list': () => import('../../components/Product/list'),
    'address-list': () => import('../../components/CommonAddress'),

  },
  props: {
    formData: Object
  },
  computed: {
  },
  watch: {
    formData: {
      immediate: true,
      handler(val) {
        this.currentId = val.product_id;
        this.productNo = val.product_no;
        this.cardType = val.card_type;
        this.isPackage = val.is_package;

        this.$nextTick(() => {
          // this.$refs.postForm.resetFields();
          // this.$refs.postForm2.resetFields();
          // this.$refs.postForm3.resetFields();
        });

        if (this.currentId > 0) {
          this.is_view = val.is_view;
          this.getDetail()
        } else if (this.productNo) {
          this.getDetail()
        } else {
          this.resetTemp();
        }
      }
    }
  },
  data() {
    return {
      redChageType: 1,
      redB: 0,
      redA: 0,
      freightTemplateList: [],
      selectedIdx: undefined,
      dialogProductVisible: false,
      productSelectForm: {
        is_select: true,
        is_sku: true,
      },
      dialogMemberVisible: false,
      dialogMemberVisibles: false,
      memberForm: {
        is_select: true
      },
      cardType: 0,
      regionGroups: [],
      productNo: "",
      batchType: "",
      batchLabel: "",
      batchForm: {
        value: undefined,
        type: 1,
      },
      dialogBatchTitle: "",
      dialogBatchVisible: false,
      editorInstance: undefined,
      editorConfig: {
        // serverUrl: process.env.VUE_APP_API_BASE + 'backend/file/na/config',
        UEDITOR_HOME_URL: process.env.BASE_URL + 'UEditor/'
      },
      props: { value: 'id', label: 'name', checkStrictly: true },
      categoryForm: {
        categoryIds: []
      },
      can_edit: true,
      memberMobile: undefined,
      address: undefined,
      form: {
        id: 0,
        shippingMethod: 1,
        title: undefined,
        parentCateId: 0,
        cateId: 0,
        thirdCateId: 0,
        hasSku: 0,
        skuInfo: [],
        minSalePrice: 0,
        minSupplyPrice: 0,
        inventory: 0,
        imgUrls: "",
        desc: undefined,
        skuList: [],
        listImgUrl: "",
        catIds: [],
        catIds2: [],
        parentCateId2: 0,
        cateId2: 0,
        thirdCateId2: 0,
        freightPrice: 0,
        productNo: undefined,
        freightTemplateId: 0,
        freeFreightNum: 0,
        limitUser: 0,
        ycProductId: 0,
        freightAmount: 0,
        useFreightTemplate: 1,
        excludeRegionIds: "",
        cardType: 0,
        isPackage: 0,
        items: [],
        virtualSaleCount: 0,
        redpacket: 0,
        cidList: [],
        minNum: 0,
        tags: 1,
        pickPointId: undefined,
        pickPointMemberId: undefined,
        isVerification: 1,
      },
      currentId: 0,
      formStatus: 'create',
      rules: {
        title: [
          {
            required: true,
            message: '请输商品名称',
            trigger: 'blur'
          }
        ],
        listImgUrl: [
          {
            required: true,
            message: '请选择商品主图',
            trigger: 'blur'
          }
        ],
        imgUrls: [
          {
            required: true,
            message: '请选择商品图片',
            trigger: 'blur'
          }
        ],
        catIds: [
          {
            required: true,
            message: '请选择商品分类',
            trigger: 'blur'
          }
        ],
        useFreightTemplate: [
          {
            required: true,
            message: '请选择运费计算方式',
            trigger: 'blur'
          }
        ],
      },
      rules2: {
      },
      rules3: {
      },
      rules4: {
      },
      rulesCard: {
        title: [
          {
            required: true,
            message: '请输商品名称',
            trigger: 'blur'
          }
        ],
        listImgUrl: [
          {
            required: true,
            message: '请选择商品主图',
            trigger: 'blur'
          }
        ],
        imgUrls: [
          {
            required: true,
            message: '请选择商品图片',
            trigger: 'blur'
          }
        ],
        useFreightTemplate: [
          {
            required: true,
            message: '请选择运费计算方式',
            trigger: 'blur'
          }
        ],
      },
      loading: false,
      fetchSuccess: true,
      saveLoading: false,
      is_view: false,
      activeName: "0",
      prevActiveName: "0",
      tree_list: [],
      dialogFormVisible: false,
      categoryList: [],
      cateList: [],
      parentCateList: [],
      skuList: [],
      showPicDialog: false,
      desc: undefined,
      isPackage: 0,
    }
  },
  created() {
    this.getFreightTemplateList();
    this.getParentCateList();
    console.log(this.form, '表单信息')
  },
  methods: {
    select() {
      // this.memberForm = {
      //     is_select: false
      // };
      // console.log(this.memberForm);
      this.dialogMemberVisible = true;
    },
    selects() {
      // this.memberForm = {
      //     is_select: false
      // };
      // console.log(this.memberForm);
      this.dialogMemberVisibles = true;
    },
    okSelectMember(item) {
      // if(item.roleId != 0) {
      //     this.$message.error("只能选择鲸粉");
      // } else {

      this.form.pickPointMemberId = item.id;
      this.memberMobile = item.mobile;
      this.dialogMemberVisibles = false;
      // }

    },
    okSelectAddress(item) {
      console.log(item)
      this.form.pickPointId = item.id;
      this.address = item.province + item.city + item.county + item.address;
      this.dialogMemberVisible = false;
    },
    // 设置红包
    changeFreightTemplateAmount(i) {
      console.log(this.redChageType, this.form.skuInfo)
      if (this.redChageType == 1) {
        // this.redB
        this.form.skuInfo.forEach(item => {
          // item.ycSalePrice = item.ycSalePrice - this.redpacket
          item.redpacket = (item.supplyPrice + item.freightPrice) * this.redB / 100
          item.profit = item.salePrice - (item.supplyPrice + item.freightPrice) * this.redB / 100 - (item.supplyPrice + item.freightPrice)
        })
      } else {
        // this.redA
        this.form.skuInfo.forEach(item => {
          // item.ycSalePrice = item.ycSalePrice - this.redpacket
          item.redpacket = this.redA
          item.profit = item.salePrice - this.redA - item.supplyPrice - item.freightPrice
        })
      }

    },
    AddSkus() {
      console.log(this.skuList)
      if (!this.skuList.length || !this.skuList[0].attrName || !this.skuList[0].items[0].attrValue) {
        this.$message.error("请选完善规格信息");
        return false
      }
      let data = {
        ycSkuInfoId: '',
        name: this.skuList.length ? this.skuList[0].attrName : '件',
        value: this.skuList[0].items.length ? this.skuList[0].items[0].attrValue : '商品',
        imgUrl: '',
        inventory: 0,
        supplyPrice: 0,
        freightPrice: 0,
        salePrice: 0,
        ycSalePrice: 0,
        virtualSaleCount: 10,
        profit: 0,
        isShow: 1,

        actualPrice: 0,
        attribute: '',
        id: 0,
        key: '',
        redpacket: 0,
      }
      this.form.skuInfo.push(data)
    },
    delSku(index) {
      this.form.skuInfo.splice(index, 1)
    },
    okSelectProduct(result) {
      this.dialogProductVisible = false;
      if (!this.form.items) {
        this.form.items = [];
      }
      // console.log("idx: " + this.selectedIdx)
      if (typeof this.selectedIdx != "undefined") {
        this.form.items[this.selectedIdx].title = result.title;
        this.form.items[this.selectedIdx].attribute = result.attribute;
        this.form.items[this.selectedIdx].productId = result.productId;
        this.form.items[this.selectedIdx].skuId = result.skuId;
        this.form.items[this.selectedIdx].price = result.price;
        this.form.items[this.selectedIdx].inventory = result.skuInventory;
        this.form.items[this.selectedIdx].salePrice = undefined;
        this.form.items[this.selectedIdx].supplyPrice = result.supplyPrice;
        this.form.items[this.selectedIdx].freightPrice = result.freightPrice;
      } else {
        this.form.items.push(result);
      }
      console.log(this.form.items)
      // product_add_to_page(
      //     {
      //         pageId: this.pageId,
      //         ids: ids
      //     }
      // ).then((res)=>{
      //     this.$message.success("商品已加入专区");
      //     this.getList();
      //     this.dialogProductVisible = false;
      // }).catch((err)=>{

      // })
      // console.log(ids)
    },
    addItem(idx) {
      this.selectedIdx = idx;
      this.dialogProductVisible = true;
    },
    removeItem(idx) {
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let final_items = [];
          this.form.items.forEach((item, i) => {
            if (i != idx) {
              final_items.push(item);
            }
          })

          this.form.items = final_items;
        }).catch(() => { });
    },
    // getRegionGroup() {
    //     region_group_list().then((res)=>{
    //         this.regionGroups = res.data;
    //     }).catch((err)=>{

    //     })
    // },
    getFreightTemplateList() {
      product_freight_template_list().then(response => {
        this.freightTemplateList = response.data;
      })
    },
    setShow(item) {
      // console.log(item)
      item.isShow = (item.isShow == 1) ? 0 : 1;
      // console.log(item)
    },
    editorReady(instance) {
      let self = this
      this.editorInstance = instance;
      // console.log(instance.iframe)

    },
    addCustomButtom(editorId) {
      const instance = this;

      window.UE.registerUI('insertimage', function (editor, uiName) {
        return new window.UE.ui.Button({
          name: uiName,
          onclick: function () {
            instance.showPicDialog = true
          }
        });
      })
    },
    picOnSelected(items) {
      if (items && items.length > 0) {
        items.forEach((item) => {
          this.editorInstance.execCommand("inserthtml", "<img src='" + item + "'>")
        })
      }
    },
    picOnClose() {
      this.showPicDialog = false
    },
    makeMinSupplyPrice() {
      let p = 0;
      if (this.form.skuInfo && this.form.skuInfo.length > 0) {
        this.form.skuInfo.forEach((item) => {
          if (item.supplyPrice) {
            if (p == 0 || item.supplyPrice < p) {
              p = item.supplyPrice;
            }
          }
        })
      }

      this.form.minSupplyPrice = p;
    },
    makeMinSalewholePrice() {
      let p = 0;
      if (this.form.skuInfo && this.form.skuInfo.length > 0) {
        this.form.skuInfo.forEach((item) => {
          if (item.wholesalePrice) {
            if (p == 0 || item.wholesalePrice < p) {
              p = item.wholesalePrice;
            }
          }
        })
      }

      this.form.minWholesalePrice = p;
    },
    makeMinSalePrice() {

      let p = 0;
      if (this.form.isPackage) {
        if (this.form.items && this.form.items.length > 0) {
          this.form.items.forEach((item) => {
            if (item.salePrice) {
              p += (parseFloat(item.salePrice) || 0)
            }
          })
        }
      } else {
        if (this.form.skuInfo && this.form.skuInfo.length > 0) {
          this.form.skuInfo.forEach((item) => {
            if (item.supplyPrice) {
              if (p == 0 || item.salePrice < p) {
                p = item.salePrice;
              }
            }
          })
        }

      }
      this.form.minSalePrice = p;
    },
    makeMinNum() {
      let p = 0;
      if (this.form.skuInfo && this.form.skuInfo.length > 0) {
        this.form.skuInfo.forEach((item) => {
          if (p == 0 || item.minNum < p) {
            p = item.minNum;
          }
        })
      }
      this.form.minNum = p;
    },
    makeMinStock() {
      let p = 0;
      if (this.form.skuInfo && this.form.skuInfo.length > 0) {
        this.form.skuInfo.forEach((item) => {
          if (item.inventory) {
            p += Number(item.inventory) || 0
          }
        })
      }
      this.form.inventory = p;
    },
    makeVirtualSaleCount() {
      let p = 0;
      if (this.form.skuInfo && this.form.skuInfo.length > 0) {
        this.form.skuInfo.forEach((item) => {
          if (item.virtualSaleCount) {
            p += Number(item.virtualSaleCount) || 0
          }
        })
      }
      this.form.virtualSaleCount = p;

    },
    getParentCateList() {
      product_cat_tree(0).then((res) => {
        this.cateList = res.data
      }).catch((err) => {
      });
    },
    resetTemp() {
      this.form = {
        id: 0,
        title: undefined,
        parentCateId: undefined,
        cateId: undefined,
        thirdCateId: undefined,
        hasSku: 0,
        skuInfo: [],
        minSalePrice: undefined,
        minSupplyPrice: undefined,
        inventory: undefined,
        imgUrls: "",
        desc: undefined,
        skuList: [],
        listImgUrl: "",
        catIds: [],
        catIds2: [],
        parentCateId2: undefined,
        cateId2: undefined,
        thirdCateId2: undefined,
        freightPrice: undefined,
        productNo: undefined,
        freightTemplateId: undefined,
        freeFreightNum: 0,
        limitUser: 0,
        ycProductId: 0,
        freightAmount: undefined,
        useFreightTemplate: this.cardType > 0 ? 0 : 1,
        excludeRegionIds: "",
        cardType: this.cardType,
        isPackage: this.isPackage,
        items: [],
        virtualSaleCount: 0,
        shippingMethod: 1,
        pickPointId: undefined,
        pickPointMemberId: undefined,
        isVerification: 1,
      };
      this.skuList = [];
      this.skuList.push(
        {
          attrName: undefined,
          items: [
            {
              attrValue: undefined
            }
          ]
        }
      )
      this.can_edit = true;
    },
    leaveTab(activeName, oldActiveName) {
      if (this.form.id > 0) {
        return true;
      }
      if (this.prevActiveName == this.activeName) {
        return false;
      }

      this.prevActiveName = this.activeName
      return true;
    },
    blurSalePrice(item) {
      let salePrice = Number(item.salePrice) || 0;
      let redpacket = Number(item.redpacket) || 0;

      item.actualPrice = salePrice - redpacket;
      item.profit = this.getProfit(item);

      console.log(item)
    },
    blurRedpacket(item) {
      let salePrice = Number(item.salePrice) || 0;
      let redpacket = Number(item.redpacket) || 0;

      item.actualPrice = salePrice - redpacket;
      item.profit = this.getProfit(item);
    },
    getDetail() {
      region_group_list().then((region_res) => {
        this.regionGroups = region_res.data;

        if (this.currentId > 0) {
          product_detail(this.currentId).then(response => {
            let form = response.data;
            this.desc = form.desc;
            this.form.desc = undefined;
            if (!form.freightTemplateId) {
              form.freightTemplateId = undefined;
            }

            this.form = form;
            if (form.pickPointMemberId) {
              this.memberMobile = form.pickPointMember.mobile;
            }
            if (form.pickPointId) {
              this.address = form.productPickPoint.province + form.productPickPoint.city + form.productPickPoint.county + form.productPickPoint.address;
            }

            this.form.catIds = [];
            if (this.form.parentCateId > 0) {
              this.form.catIds.push("" + this.form.parentCateId + "");

              if (this.form.cateId > 0) {
                this.form.catIds.push("" + this.form.cateId + "");
              }

              if (this.form.thirdCateId > 0) {
                this.form.catIds.push("" + this.form.thirdCateId + "");
              }
              //     this.getCateList(true);
            }

            this.form.catIds2 = [];
            if (this.form.parentCateId2 > 0) {
              this.form.catIds2.push("" + this.form.parentCateId2 + "");

              if (this.form.cateId2 > 0) {
                this.form.catIds2.push("" + this.form.cateId2 + "");
              }

              if (this.form.thirdCateId2 > 0) {
                this.form.catIds2.push("" + this.form.thirdCateId2 + "");
              }
              //     this.getCateList(true);
            }
            // if(!this.form.skuInfo) {
            //     this.form.skuInfo = [];
            // }

            // console.log(this.form)
            this.skuList = this.form.skuList;

            if (!this.skuList || this.skuList.length < 1) {
              this.skuList = [];
              this.skuList.push(
                {
                  attrName: undefined,
                  items: [
                    {
                      attrValue: undefined
                    }
                  ]
                }
              )
            }

            let excludeRegions = [];
            if (this.form.excludeRegionIds) {
              let a = this.form.excludeRegionIds.split(",");
              a.forEach((item) => {
                if (item && item > 0) {
                  this.regionGroups.forEach((item2) => {
                    let has = false;
                    item2.areas.forEach((item3) => {
                      if (item3.id == item) {
                        excludeRegions.push(
                          [
                            item2.id,
                            item3.id
                          ]
                        )
                        has = true;
                        return false;
                      } else {
                        item3.areas.forEach((item4) => {
                          if (item4.id == item) {
                            excludeRegions.push(
                              [
                                item2.id,
                                item3.id,
                                item4.id
                              ]
                            )
                            has = true;
                            return false;
                          }
                        });

                        if (has) {
                          return false;
                        }
                      }
                    })

                    if (has) {
                      return false;
                    }
                  })
                }
              })
            }

            this.form.excludeRegions = excludeRegions;
            console.log(excludeRegions)

            if (this.form.ycProductId > 0) {
              yc_detail(this.form.ycProductId).then((yc_res) => {
                //用远程信息填充下
                this.form.ycProductId = yc_res.data.id;
                this.form.imgUrls = yc_res.data.imgUrls
                this.form.listImgUrl = yc_res.data.listImgUrl
                this.form.isVerification = yc_res.data.isVerification;
                let minSalePrice = yc_res.data.minSalePrice;
                let hasSalePrice = false;

                let newSkuInfo = [];
                if (yc_res.data.skuInfo) {
                  yc_res.data.skuInfo.forEach((item) => {
                    let id = 0, redpacket = 0, isShow = 1, salePrice = 0, virtualSaleCount = 0;

                    this.form.skuInfo.forEach((item2) => {
                      if (item2.ycSkuInfoId == item.id) {
                        id = item2.id;
                        redpacket = item2.redpacket
                        isShow = item2.isShow
                        salePrice = item2.salePrice
                        virtualSaleCount = item2.virtualSaleCount;

                        if (!hasSalePrice) {
                          minSalePrice = salePrice;
                          hasSalePrice = true;
                        }
                        return false;
                      }
                    });
                    let actualPrice = salePrice - redpacket;

                    newSkuInfo.push(
                      {
                        id: id,
                        key: item.key,
                        name: item.name,
                        value: item.value,
                        imgUrl: item.imgUrl,
                        inventory: item.inventory,
                        salePrice: salePrice,
                        ycSalePrice: item.salePrice,
                        supplyPrice: item.wholesalePrice,
                        freightPrice: yc_res.data.freightPrice,
                        attribute: item.attribute,
                        ycSkuInfoId: item.id,
                        redpacket: redpacket,
                        isShow: isShow,
                        actualPrice: actualPrice,
                        virtualSaleCount: virtualSaleCount,
                        profit: this.getProfit(
                          {
                            actualPrice: actualPrice,
                            supplyPrice: item.wholesalePrice,
                            redpacket: redpacket,
                          }
                        )
                      }
                    );
                  })
                }
                this.form.skuInfo = newSkuInfo;

                let newSkuList = [];
                if (yc_res.data.skuList) {
                  let id = 0, items = [];
                  yc_res.data.skuList.forEach((item) => {
                    this.skuList.forEach((item2) => {
                      if (item2.ycSkuId == item.id) {
                        id = item2.id;
                        items = item2.items;
                        return false;
                      }
                    })

                    let newItems = [];
                    item.items.forEach((item3) => {
                      let itemId = 0;

                      items.forEach((item4) => {
                        if (item4.ycSkuItemId == item3.id) {
                          itemId = item4.id;
                          return false;
                        }
                      })
                      newItems.push(
                        {
                          id: itemId,
                          ycSkuItemId: item3.id,
                          key: item3.key,
                          attrValue: item3.attrValue
                        }
                      )
                    })

                    newSkuList.push(
                      {
                        id: id,
                        ycSkuId: item.id,
                        key: item.key,
                        attrName: item.attrName,
                        items: newItems,
                      }
                    )
                  });
                }

                this.skuList = newSkuList;

                this.form.minSalePrice = minSalePrice;
                this.form.minSupplyPrice = yc_res.data.minWholesalePrice;
                this.form.inventory = yc_res.data.inventory;
                this.form.desc = yc_res.data.desc;
                this.form.freightPrice = yc_res.data.freightPrice;
                this.form.freightAmount = yc_res.data.freightPrice;
                // console.log(newSkuList)

                // console.log(newSkuInfo)
              }).catch((yc_err) => {

              });

            }
            this.formStatus = "update";
            this.can_edit = true
          }).catch(() => {
            this.formStatus = ""
          });
        } else if (this.productNo) {
          yc_detail(this.productNo).then((res) => {
            this.form.ycProductId = res.data.id;
            this.form.title = res.data.title
            this.form.imgUrls = res.data.imgUrls
            this.form.listImgUrl = res.data.listImgUrl
            this.form.productNo = this.productNo
            this.form.hasSku = 1
            this.form.skuInfo = res.data.skuInfo

            let skuList = res.data.skuList;
            if (skuList && skuList.length > 0) {
              skuList.forEach((item) => {
                item.ycSkuId = item.id;
                item.id = 0;
                if (item.items && item.items.length > 0) {
                  item.items.forEach((item2) => {
                    item2.ycSkuItemId = item2.id;
                    item2.id = 0;
                  })
                }
              })
            }
            this.skuList = skuList;

            let skuInfo = [];
            if (res.data.skuInfo && res.data.skuInfo.length > 0) {
              res.data.skuInfo.forEach((item) => {
                let salePrice = item.wholesalePrice + res.data.freightPrice;

                skuInfo.push(
                  {
                    id: 0,
                    key: item.key,
                    name: item.name,
                    value: item.value,
                    imgUrl: item.imgUrl,
                    inventory: item.inventory,
                    salePrice: salePrice,
                    ycSalePrice: item.salePrice,
                    supplyPrice: item.wholesalePrice,
                    attribute: item.attribute,
                    freightPrice: res.data.freightPrice,
                    isShow: 1,
                    ycSkuInfoId: item.id,
                    redpacket: item.redpacket ? item.redpacket : 0,
                    actualPrice: salePrice,
                    virtualSaleCount: 0,
                    profit: this.getProfit(
                      {
                        actualPrice: salePrice,
                        supplyPrice: item.wholesalePrice,
                        redpacket: 0,
                      }
                    )
                  }
                )
              })
            }
            this.form.skuInfo = skuInfo;
            this.form.minSalePrice = res.data.minSalePrice;
            this.form.minSupplyPrice = res.data.minWholesalePrice;
            this.form.inventory = res.data.inventory;
            this.form.desc = res.data.desc;
            this.form.freightPrice = res.data.freightPrice;
            this.form.freightAmount = res.data.freightPrice;
            this.form.isVerification = res.data.isVerification;
            // console.log(this.form.skuInfo);
            // console.log(this.skuList)
          }).catch((err) => {

          })
        }
      }).catch((region_err) => {

      })
      console.log(this.form, '########################')
    },
    cancel() {
      this.$emit('cancelCreate');
    },
    finalSave() {
      console.log(this.form)
      if (!this.form.skuInfo.length) {
        this.$message.error("产品规格必填");
        return false
      }
      this.form.skuList = [];
      console.log(this.skuList)
      if (this.skuList && this.skuList.length > 0) {
        this.skuList.forEach((item, idx) => {
          let finalItem = [];
          if (item && item.attrName && item.items && item.items.length > 0) {
            item.items.forEach((item2, idx2) => {
              if (item2.attrValue) {
                item2.key = idx2;

                finalItem.push(item2);
              }
            })
          }

          if (finalItem.length > 0) {
            this.form.skuList.push(
              {
                id: item.id,
                items: finalItem,
                key: idx,
                attrName: item.attrName,
                ycSkuId: item.ycSkuId,
              }
            )
          }
        })
      }
      this.form.parentCateId = (this.form.catIds && this.form.catIds.length > 0) ? this.form.catIds[0] : 0;
      this.form.cateId = (this.form.catIds && this.form.catIds.length > 1) ? this.form.catIds[1] : 0;
      this.form.thirdCateId = (this.form.catIds && this.form.catIds.length > 2) ? this.form.catIds[2] : 0;

      this.form.parentCateId2 = (this.form.catIds2 && this.form.catIds2.length > 0) ? this.form.catIds2[0] : 0;
      this.form.cateId2 = (this.form.catIds2 && this.form.catIds2.length > 1) ? this.form.catIds2[1] : 0;
      this.form.thirdCateId2 = (this.form.catIds2 && this.form.catIds2.length > 2) ? this.form.catIds2[2] : 0;


      let excludeRegionIds = [];
      if (this.form.excludeRegions && this.form.excludeRegions.length > 0) {
        this.form.excludeRegions.forEach((item) => {
          if (item) {
            excludeRegionIds.push(item[item.length - 1]);
          }
        })
      }
      this.form.excludeRegionIds = excludeRegionIds.join(",");

      this.saveLoading = true;

      console.log(this.form)
      product_save(this.form)
        .then(() => {
          this.saveLoading = false;
          this.$message.success(this.form.id > 0 ? "商品信息已保存" : "成功添加商品");
          this.$emit('okCreate', {
            cardType: this.form.cardType,
            isPackage: this.form.isPackage,
          });
        }).catch((err) => {
          this.saveLoading = false;
        })

    },
    next() {
      // if(1==1){
      //     console.log(this.form.skuInfo)
      //     return
      // }

      let form = "";
      if (this.activeName == "0") {
        form = "postForm";
      } else if (this.activeName == "1") {
        form = "postForm2";
      } else if (this.activeName == "2") {
        form = "postForm3";
      }

      if (form) {
        this.$refs[form].validate(valid => {
          if (valid) {
            let nextStep = this.form.isPackage ? 2 : (this.form.cardType > 0 ? 2 : 1);
            if (this.activeName == nextStep) {
              //最后一步
              if (this.form.ycProductId > 0) {
                //检查供货成本
                if (this.form.hasSku == "1") {
                  let hasInvalid = false;
                  this.form.skuInfo.forEach((item) => {
                    let cb = parseFloat(item.supplyPrice) || 0;
                    cb += (parseFloat(item.freightPrice) || 0);

                    let sj = parseFloat(item.salePrice) || 0;

                    if (sj < cb) {
                      hasInvalid = true;
                      this.$confirm('您设置的零售价低于供货价，是否确认?', '提示', {
                        confirmButtonText: '确认',
                        cancelButtonText: '去修改',
                        type: 'warning'
                      })
                        .then(() => {
                          this.finalSave();
                        }).catch(() => { });
                      return false;
                    }
                  });

                  if (!hasInvalid) {
                    this.finalSave();
                  }
                } else {
                  this.finalSave();
                }
              } else {
                this.finalSave();
              }
              // this.form.listImgUrl = "";
              // if(this.form.imgUrls) {
              //     let a = this.form.imgUrls.split(",");
              //     this.form.listImgUrl = a[0];
              // }

            } else {
              this.prevActiveName = this.activeName

              if (this.form.isPackage) {
                this.activeName = "2";
              } else {
                this.activeName = "" + (parseInt(this.activeName) + 1) + "";
              }
            }
          }
        });
      }
    },
    prev() {
      this.prevActiveName = this.activeName
      if (this.form.isPackage) {
        this.activeName = "0";
      } else {
        this.activeName = "" + (parseInt(this.activeName) - 1) + "";
      }
    },
    handleClick(tab, event) {
      // this.prevActiveName = this.activeName
      // console.log(this.prevActiveName + "-" + this.activeName)
    },
    removeSku(idx) {
      this.$confirm('删除会重置规格明细, 是否操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let l = [];
        this.skuList.forEach((item, i) => {
          if (item && i != idx) {
            l.push(item);
          }
        })

        if (l.length > 0) {
          this.skuList = l;
          // console.log(this.skuList)
          this.finalMakeSku();

        }
      })
    },
    delete_item(idx) {
      this.$confirm('确定删除这个类目吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let items = [];

          this.categoryList.forEach((item, item_idx) => {
            if (item_idx != idx) {
              items.push(item);
            }
          })

          this.categoryList = items;
        }).catch(() => { });
    },
    addSku() {
      this.skuList.push(
        {
          attrName: undefined,
          items: [
            {
              attrValue: undefined
            }
          ]
        }
      )
    },
    getSkuPlaceHolder(idx) {
      return "请填写规格值" + (idx + 1)
    },
    addSkuItem(idx) {
      this.skuList[idx].items.push(
        {
          attrValue: undefined
        }
      )
      this.skuList[idx].items.push(
        {
          attrValue: undefined
        }
      )
      this.skuList[idx].items.push(
        {
          attrValue: undefined
        }
      )
      this.skuList[idx].items.push(
        {
          attrValue: undefined
        }
      )
    },
    concatSkuArr(arr1, arr2) {
      let r = [];
      arr1.forEach((item) => {
        arr2.forEach((item2) => {
          let n = item + "," + item2;
          r.push({
            key: item.key + "," + item2.key,
            name: item.name + "," + item2.name,
            value: item.value + "," + item2.value,
            attribute: item.attribute + ", " + item2.attribute
          })
        })
      })


      return r;
    },
    finalMakeSku() {
      var list = [];
      for (var i = 0; i < this.skuList.length; i++) {
        if (this.skuList[i] && this.skuList[i].items && this.skuList[i].items.length > 0) {
          if (!this.skuList[i].attrName) {
            continue;
          }
          let t = [];
          for (var j = 0; j < this.skuList[i].items.length; j++) {
            if (!this.skuList[i].items[j].attrValue) {
              continue;
            }
            let k = i + ":" + j;
            t.push(
              {
                key: k,
                name: this.skuList[i].attrName,
                value: this.skuList[i].items[j].attrValue,
                attribute: this.skuList[i].attrName + ":" + this.skuList[i].items[j].attrValue
              }
            )
          }
          if (list.length > 0) {
            list = this.concatSkuArr(list, t);
          } else {
            list = t.slice();
          }
        }
      }
      // console.log(list)

      list.forEach((item) => {
        item.imgUrl = undefined;
        item.inventory = undefined;
        item.salePrice = undefined;
        item.supplyPrice = undefined;
      });

      this.form.skuInfo = list;
    },
    getProfit(obj) {
      if (this.form.cardType > 0) {
        return 0;
      }
      return (Number(obj.actualPrice) - Number(obj.supplyPrice) - (Number(this.form.freightPrice) || 0)).toFixed(2);
      // return (Number(obj.actualPrice) + Number(obj.redpacket) / 5.1 - Number(obj.supplyPrice) - (Number(this.form.freightPrice) || 0)).toFixed(2);
    },
    makeSku() {
      this.$confirm('生成规格明细会重置列表, 是否操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        this.finalMakeSku();
      })
    },
    batchSupplyPrice() {
      this.dialogBatchTitle = "批量设置供货价";
      this.batchForm.value = undefined;
      this.batchLabel = "供货价";
      this.batchType = "supply";
      this.dialogBatchVisible = true;
    },
    batchSalePrice() {
      this.dialogBatchTitle = "批量设置售价";
      this.batchForm.value = undefined;
      this.batchLabel = "售价";
      this.batchType = "sale";
      this.dialogBatchVisible = true;
    },
    batchVirtualSaleCount() {
      this.dialogBatchTitle = "批量设置虚拟销量";
      this.batchForm.value = undefined;
      this.batchLabel = "虚拟销量";
      this.batchType = "virtual_sale_count";
      this.dialogBatchVisible = true;
    },
    batchRedpacket() {
      this.dialogBatchTitle = "批量设置红包抵扣";
      this.batchForm.value = undefined;
      this.batchLabel = "红包抵扣";
      this.batchType = "redpacket";
      this.dialogBatchVisible = true;
    },
    batchWholesalePrice() {
      this.dialogBatchTitle = "批量设置批发价";
      this.batchForm.value = undefined;
      this.batchLabel = "批发价";
      this.batchType = "wholesale";
      this.dialogBatchVisible = true;
    },
    okBatch() {
      if (typeof this.batchForm.value == "undefined") {
        this.$message.error("批量数值必填");
      } else {
        let v = $.trim(this.batchForm.value);

        if (v.length < 1) {
          this.$message.error("批量数值必填");
        } else {
          v = Number(v) || 0;

          if (this.form.skuInfo && this.form.skuInfo.length > 0) {
            this.form.skuInfo.forEach((item) => {
              if (this.batchType == "supply") {
                item.supplyPrice = v;
              } else if (this.batchType == "sale") {
                if (this.batchForm.type == 1) {
                  //上浮比例
                  let vv = parseFloat(item.salePrice) || 0;
                  item.salePrice = (vv * (1 + v / 100)).toFixed(2);
                  // console.log(vv + "-" + v)
                } else {
                  item.salePrice = v;
                }
                this.blurSalePrice(item);
              } else if (this.batchType == "wholesale") {
                if (this.batchForm.type == 1) {
                  //上浮比例
                  let vv = parseFloat(item.supplyPrice) || 0;
                  item.wholesalePrice = (vv * (1 + v / 100)).toFixed(2)
                } else {
                  item.wholesalePrice = v;
                }
              } else if (this.batchType == "redpacket") {
                item.redpacket = v;
                this.blurRedpacket(item);
              } else if (this.batchType == "inventory") {
                item.inventory = v;
              } else if (this.batchType == "virtual_sale_count") {
                item.virtualSaleCount = v;
              }
            })
          }

          if (this.batchType == "supply") {
            this.makeMinSupplyPrice();
          } else if (this.batchType == "sale") {
            this.makeMinSalePrice();
          } else if (this.batchType == "wholesale") {
            this.makeMinSalewholePrice();
          } else if (this.batchType == "inventory") {
            this.makeMinStock();
          } else if (this.batchType == "virtual_sale_count") {
            this.makeVirtualSaleCount();
          }
          this.dialogBatchVisible = false;
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.note_back {
  line-height: 32px;
}

.w200 {
  width: 220px;
}

.attr_box {
  background: #f3f3f3;
  padding-top: 17px;
  border-radius: 4px;

  .item {
    position: relative;

    .line {
      padding-left: 70px;
      padding-right: 30px;
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-align: center;
      -ms-flex-align: center;
      align-items: center;
      position: relative;
      font-size: 14px;
      -ms-flex-wrap: wrap;
      flex-wrap: wrap;

      .name {
        position: absolute;
        top: 0;
        left: 20px;
        line-height: 34px;
        text-align: center;
        color: #333;
      }

      .line-val {
        width: 240px;
        margin: 0 20px 4px 0;
      }

      .delete {
        right: 20px;
        top: 0;
        position: absolute;
      }

      .add {
        left: 70px;
        bottom: 0;
        position: absolute;

      }
    }

  }
}
</style>
